package com.os.config;

import org.aopalliance.intercept.Joinpoint;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.*;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Component;

/**
 * @Author Matt
 * @Date 2022-01-09
 * @Desc: service的方法执行需要多少时间统计
 * @Version V1.0
 */
@Aspect
@Component
public class LogServiceTakeTime {

    final static Logger log = LoggerFactory.getLogger(LogServiceTakeTime.class);

    //拦截这个包下面的任何类，以及其子包下面的任何类
    @Pointcut("execution(* com.os.start.service..*.*(..))")
    public void performance(){

    }

    @Around("performance()")
    public Object doLog(ProceedingJoinPoint joinPoint) throws Throwable {
        //记录起始时间
        long begin = System.currentTimeMillis();
        Object result = "";
        //执行目标方法
        try {
            result = joinPoint.proceed();
        }catch (Exception e){
            log.error("日志记录发生错误，errorMessage：{}", e.getMessage());
        }finally{
            //记录操作时间
            long took = System.currentTimeMillis() - begin;

            log.info("service执行时间：{}毫秒", took);

            if(took >= 10000){
                log.error("service执行时间为：{}毫秒", took);
            }else if(took >= 5000){
                log.warn("service执行时间为：{}毫秒", took);
            }else if(took >= 3000){
                log.info("service执行时间为：{}毫秒", took);
            }
            //todo 日志保存到mongoDB中，保存然后统一管理
        }
        return result;
    }

    @Before("performance()")
    public void doBefore() throws Throwable{
        //收到请求，记录请求内容
        log.info("doBefore");
    }

    @AfterReturning(returning = "ret", pointcut = "performance()")
    public void doAfterReturning(Object ret) throws Throwable{
        //处理完请求，返回内容
        log.info("doAfterReturning");
    }

}
